package com.yami.shop.api.controller;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yami.shop.bean.event.ProdRightsEvent;
import com.yami.shop.bean.model.*;
import com.yami.shop.bean.param.EsProductParam;
import com.yami.shop.bean.vo.search.MicroreleaseProductListVO;
import com.yami.shop.bean.vo.search.MicroreleaseProductSearchVo;
import com.yami.shop.bean.vo.search.ProdRightSearchVO;
import com.yami.shop.common.bean.PageDTO;
import com.yami.shop.common.bean.PageVO;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.EsPageVO;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.mystery.common.dto.ActivityPresellDto;
import com.yami.shop.mystery.common.model.ActivityPresell;
import com.yami.shop.mystery.common.model.ActivitySubject;
import com.yami.shop.mystery.common.model.MysteryBox;
import com.yami.shop.mystery.common.service.ActivityPresellService;
import com.yami.shop.mystery.common.service.ActivityReceiveRecordService;
import com.yami.shop.mystery.common.service.ActivitySubjectService;
import com.yami.shop.mystery.common.service.MysteryBoxService;
import com.yami.shop.rights.common.model.ProdRights;
import com.yami.shop.rights.common.service.ProdRightsService;
import com.yami.shop.search.common.param.EsPageParam;
import com.yami.shop.search.common.service.SearchProductService;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.concurrent.ConcurrentUtils;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/activity/receive")
@Tag(name="零元购领取接口")
@Slf4j
public class ActivityReceiveRecordController {

    @Autowired
    private ActivityReceiveRecordService activityReceiveRecordService;

    @Autowired
    private ActivityPresellService activityPresellService;
    @Autowired
    private ActivitySubjectService activitySubjectService;

    @Autowired
    private SearchProductService searchProductService;

    @Autowired
    private ChannelUserRelationRecordService channelUserRelationRecordService;

    @Autowired
    private ProductService prodService;

    @Autowired
    private ProdNftService prodNftService;
    @Autowired
    private ProdRightsService prodRightsService;
    @Autowired
    private MysteryBoxService mysteryBoxService;
    @Autowired
    private ProdLevelService prodLevelService;
    @Autowired
    private ShopDetailService shopDetailService;

    @GetMapping("/page")
    @Operation(summary =  "个人领取记录", description = "个人领取记录")
    public ServerResponseEntity<PageVO<ActivityReceiveRecord>> pageListbyUserId(PageDTO pageDTO,String userId,String shopId) {
        return ServerResponseEntity.success(activityReceiveRecordService.pageListbyUserId(pageDTO, userId,shopId));
    }

    @PostMapping("/receive")
    @Operation(summary =  "零元购领取", description = "零元购领取")
    public ServerResponseEntity<Void> receive(@RequestBody ActivityReceiveRecord activityReceiveRecord) {
        activityReceiveRecordService.receive(activityReceiveRecord);
        return ServerResponseEntity.success();
    }

    @GetMapping("/getProdInfo")
    @Operation(summary =  "获取免费领取商品信息", description = "根据商品ID（prodId）获取商品信息")
    public ServerResponseEntity<MicroreleaseProductSearchVo> recommend(Long prodId,String userId,Long activityId) {
        MicroreleaseProductSearchVo productSearchVO = new MicroreleaseProductSearchVo();
        // 获取活动详情
        ActivityPresell byId = activityPresellService.getById(activityId);
        if(byId.getBlindType() == 0){
            productSearchVO.setIndexIdPrefix("prod");
            Product product = prodService.getProductInfo(prodId);
            if (product == null || product.getStatus() == -1 || product.getStatus() == 0) {
                // 商品已下线
                throw new YamiShopBindException("yami.product.off.shelves");
            }
            cn.hutool.core.bean.BeanUtil.copyProperties(product, productSearchVO);
        }else {
            MysteryBox detail = mysteryBoxService.detail(prodId);
            cn.hutool.core.bean.BeanUtil.copyProperties(detail, productSearchVO);
            productSearchVO.setProdId(detail.getId());
            productSearchVO.setProdName(detail.getBoxName());
            productSearchVO.setAuthorName(detail.getAuthor());
            productSearchVO.setIssueName(detail.getIssue());
            productSearchVO.setCirculation(detail.getTotalStocks());
            productSearchVO.setMold(3);
            productSearchVO.setIndexIdPrefix("box");
            // 获取渠道CODE
            ShopDetail shopDetailByShopId = shopDetailService.getShopDetailByShopId(detail.getShopId());
            productSearchVO.setChannelCode(shopDetailByShopId.getChannelCode());
            if(!ObjectUtil.isNull(detail.getLevelId())){
                ProdLevel prodLevelData = prodLevelService.getById(detail.getLevelId());
                productSearchVO.setProdLevel(prodLevelData);
            }
        }
        // 获取虚拟商品
        if (productSearchVO.getMold() == 2) {
            ProdNft dataByProdId = prodNftService.getDataByProdId(prodId);
            cn.hutool.core.bean.BeanUtil.copyProperties(dataByProdId, productSearchVO, "chain");
            productSearchVO.setIsRights(ObjectUtil.isNotEmpty(dataByProdId.getRightsId()) ? 1 : 0);
            if(ObjectUtil.isNotEmpty(dataByProdId.getRightsId())){
                // 获取权益信息
                QueryWrapper<ProdRights> prodRightsQueryWrapper = new QueryWrapper<>();
                prodRightsQueryWrapper.ne("status",-1);
                prodRightsQueryWrapper.in("id",Arrays.asList(dataByProdId.getRightsId().split(",")));
                List<ProdRights> list = prodRightsService.list(prodRightsQueryWrapper);
                productSearchVO.setProdRights(cn.hutool.core.bean.BeanUtil.copyToList(list, ProdRightSearchVO.class));
            }
        }

        if (ObjectUtil.isNotEmpty(userId)) {
            // 该用户是否绑定链
            Boolean hasDTCAddress = channelUserRelationRecordService.isHasDTCAddress(userId, productSearchVO.getChain(), productSearchVO.getChannelCode());
            productSearchVO.setIsHasDTCAddress(hasDTCAddress);
            productSearchVO.setChainCode(productSearchVO.getChain());
        }else {
            // 通过商品ID查活动信息
            List<ActivityPresellDto> activityPresellDtos = activityPresellService.selectAllActivityPresellByProdId(prodId);
            if(ObjectUtil.isNotEmpty(activityPresellDtos)){
                ActivityPresellDto activityPresellDto = activityPresellDtos.get(0);
                if(ObjectUtil.isNotEmpty(activityPresellDto)){
                    productSearchVO.setStartTime(activityPresellDto.getPutawayTime());
                    productSearchVO.setRuleMaxNum(activityPresellDto.getRuleMaxNum());
                }
            }
        }

        // isReceive 是否可以领取
        productSearchVO.setIsReceive(true);
        LambdaQueryWrapper<ActivityReceiveRecord> eq = new LambdaQueryWrapper<ActivityReceiveRecord>()
                .eq(ActivityReceiveRecord::getProdId, prodId)
                .eq(ActivityReceiveRecord::getUserId, userId)
                .eq(ActivityReceiveRecord::getActivityId,activityId);
        List<ActivityReceiveRecord> receiveRecordList = activityReceiveRecordService.list(eq);
        if(ObjectUtils.isNotEmpty(receiveRecordList)){
            productSearchVO.setIsReceive(false);
        }
        return ServerResponseEntity.success(productSearchVO);
    }


    /**
     * 功能描述: 未登录下 微发行商品列表
     * @Author: LSR
     * @Date: 2023/4/19 18:50
     */
    @GetMapping("/microreleaseList")
    @Operation(summary =  "微发行零元购商品列表", description = "微发行零元购商品列表")
    public ServerResponseEntity<EsPageVO<MicroreleaseProductSearchVo>> microreleaseList(PageParam page, @ParameterObject EsProductParam productParam) {
        if(ObjectUtil.isEmpty(productParam.getShopId())){
            return ServerResponseEntity.success();
        }
        // 获取开启活动的活动ID
        List<ActivityPresellDto> activityPresellDtos = activityPresellService.selectAllActivityPresellByActivityType(4);
        if(ObjectUtils.isEmpty(activityPresellDtos)){
            return ServerResponseEntity.success();
        }
        // 根据ID转化为Map
        Map<Long, ActivityPresellDto> activityPresellMap = activityPresellDtos.stream().collect(Collectors.toMap(ActivityPresellDto::getId, Function.identity()));
        List<Long> activityIds = activityPresellDtos.stream().map(ActivityPresellDto::getId).collect(Collectors.toList());
        productParam.setActivityIds(activityIds);
        productParam.setProdType(8);
//        productParam.setAppDisplay(false);
        EsPageParam esPageParam = new EsPageParam();
        esPageParam.setCurrent((int) page.getCurrent());
        esPageParam.setSize((int) page.getSize());
        EsPageVO<MicroreleaseProductSearchVo> productPage = searchProductService.microreleasePage(esPageParam, productParam, Boolean.FALSE);
        // 循环组装数据
        for (MicroreleaseProductSearchVo microreleaseProductSearchVo : productPage.getRecords()) {
            // 没有活动获取商品默认限购数
            microreleaseProductSearchVo.setRuleMaxNum(microreleaseProductSearchVo.getMaxNum());
            if (microreleaseProductSearchVo.getActivityId() != 0) {
                ActivityPresellDto activityPresellDto = activityPresellMap.get(microreleaseProductSearchVo.getActivityId());
                if (ObjectUtil.isNotEmpty(activityPresellDto)) {
                    if(ObjectUtil.isNotEmpty(activityPresellDto.getMaxNum()) && activityPresellDto.getMaxNum() > 0){
                        microreleaseProductSearchVo.setMaxNum(activityPresellDto.getMaxNum());
                    }
                    if(ObjectUtil.isNotEmpty(activityPresellDto.getRuleMaxNum()) && activityPresellDto.getRuleMaxNum() > 0){
                        microreleaseProductSearchVo.setRuleMaxNum(activityPresellDto.getRuleMaxNum());
                    }
                    microreleaseProductSearchVo.setStartTime(activityPresellDto.getPutawayTime());
                }
            }
        }
        return ServerResponseEntity.success(productPage);
    }

    @GetMapping("/microreleaseListByActivitySubjectId")
    @Operation(summary =  "微发行零元购商品列表通过活动专题ID查询", description = "微发行零元购商品列表通过活动专题ID查询")
    public ServerResponseEntity<EsPageVO<MicroreleaseProductSearchVo>> microreleaseListByActivitySubjectId(PageParam page, @ParameterObject EsProductParam productParam) {
        if(ObjectUtil.isEmpty(productParam.getActivitySubjectId())){
            return ServerResponseEntity.success();
        }
        // 获取活动
        ActivitySubject byId = activitySubjectService.getById(productParam.getActivitySubjectId());
        if(ObjectUtils.isEmpty(byId)){
            return ServerResponseEntity.success();
        }
        // 获取开启活动的活动ID
        List<ActivityPresellDto> activityPresellDtos = activityPresellService.selectAllActivityPresellByActivityIds(Arrays.asList(byId.getActivityId().split(",")), Collections.singletonList(4L));
        if(ObjectUtils.isEmpty(activityPresellDtos)){
            return ServerResponseEntity.success();
        }
        // 根据ID转化为Map
        Map<Long, ActivityPresellDto> activityPresellMap = activityPresellDtos.stream().collect(Collectors.toMap(ActivityPresellDto::getId, u->u,(key1,key2) -> key1));
        List<Long> activityIds = activityPresellDtos.stream().map(ActivityPresellDto::getId).collect(Collectors.toList());
        productParam.setActivityIds(activityIds);
        productParam.setProdType(8);
//        productParam.setAppDisplay(false);
        EsPageParam esPageParam = new EsPageParam();
        esPageParam.setCurrent((int) page.getCurrent());
        esPageParam.setSize((int) page.getSize());
        EsPageVO<MicroreleaseProductSearchVo> productPage = searchProductService.microreleasePage(esPageParam, productParam, Boolean.FALSE);
        // 循环组装数据
        for (MicroreleaseProductSearchVo microreleaseProductSearchVo : productPage.getRecords()) {
            // 没有活动获取商品默认限购数
            microreleaseProductSearchVo.setRuleMaxNum(microreleaseProductSearchVo.getMaxNum());
            if (microreleaseProductSearchVo.getActivityId() != 0) {
                ActivityPresellDto activityPresellDto = activityPresellMap.get(microreleaseProductSearchVo.getActivityId());
                if (ObjectUtil.isNotEmpty(activityPresellDto)) {
                    if(ObjectUtil.isNotEmpty(activityPresellDto.getMaxNum()) && activityPresellDto.getMaxNum() > 0){
                        microreleaseProductSearchVo.setMaxNum(activityPresellDto.getMaxNum());
                    }
                    if(ObjectUtil.isNotEmpty(activityPresellDto.getRuleMaxNum()) && activityPresellDto.getRuleMaxNum() > 0){
                        microreleaseProductSearchVo.setRuleMaxNum(activityPresellDto.getRuleMaxNum());
                    }
                    microreleaseProductSearchVo.setStartTime(activityPresellDto.getPutawayTime());
                }
            }
        }
        return ServerResponseEntity.success(productPage);
    }
}
